var express = require('express');
var router = express.Router();
const User = require('../model/User/index')
const JwtToekn = require('../util/JwtToken')
const { hash, compare } = require('../util/encryption')

/* 用户注册 */
router.post('/register', async(req, res, next) => {
    let body = req.body;
    // 查询用户是否存在
    const result = await User.findOne({
        where: {
            username: body.username
        }
    })
    if (result === null) {
        body.password = await hash(body.password)
        await User.create(body)
        res.json({
            code: 200,
            msg: '注册成功'
        })
    } else {
        res.json({
            code: 500,
            msg: '用户已存在'
        })
    }
});

/* 用户登录 */
router.post('/login', async(req, res) => {
    let body = req.body;

    const result = await User.findOne({
        where: {
            username: body.username
        }
    });

    if (result) {
        // 密码比较
        let pasRes = await compare(body.password, result.password)

        if (pasRes) {
            let token = JwtToekn.encrypt(body)
            res.json({
                code: 200,
                data: {
                    token: token
                },
                msg: '登录成功'
            })
        } else {
            res.json({
                code: 500,
                msg: '登录失败，密码不对'
            })
        }
    } else {
        res.json({
            code: 500,
            msg: '登录失败，账号不存在'
        })
    }
});

/* 用户修改 */
router.post('/update', async(req, res) => {
    let body = req.body;

    // 查询用户 是否存在
    const result = await User.findOne({
        where: {
            id: body.uid
        }
    });
    if (result !== null) {
        await User.update({ username, password } = body, {
            where: {
                id: body.uid
            }
        })
    } else {
        res.json({
            code: 500,
            msg: '用户不存在'
        })
    }

});

/* 获取用户信息 */
router.get('/getUser', async(req, res) => {
    let body = req.body;

    // 查询用户 是否存在
    const result = await User.findOne({
        where: {
            id: body.uid
        }
    });
    if (result !== null) {
        res.json({
            code: 200,
            data: result
        })
    }

});


module.exports = router;